package com.btl.service.ai.biz.adaptor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.btl.boot.core.dto.response.R;
import com.btl.service.ai.auth.SecurityContextHolder;
import com.btl.service.ai.biz.constants.FunModuleEnum;
import com.btl.service.ai.biz.entity.ChatMemory;
import com.btl.service.ai.biz.service.IChatHistoryService;
import com.btl.service.ai.biz.service.IChatMemoryService;
import com.btl.service.ai.support.rag.store.rdb.table.ChatHistory;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Tim
 * @since 2025-08-11
 */
@Slf4j
@Validated
@RestController
@Tag(name = "记忆")
@Controller
@RequestMapping("memory")
public class ChatMemoryController {

    @Resource
    private IChatMemoryService iChatMemoryService;

    @Resource
    private IChatHistoryService iChatHistoryService;

    /**
     * 记忆会话
     *
     * @param socialSelfId 社交ID
     * @param funModel     功能模块
     * @return List<SplitSegmentRsp>
     */
    @GetMapping(value = "/get")
    @Transactional(rollbackFor = Exception.class)
    public R<Map<String, Object>> get(
            @RequestParam(value = "socialSelfId", required = false) @NotBlank(message = "社交ID不能为空") String socialSelfId,
            @RequestParam(value = "funModel", required = false) @NotNull(message = "功能模块不能为空") FunModuleEnum funModel) {
        Long childId = SecurityContextHolder.get()
                .getChildId();
        ChatMemory chatMemory = iChatMemoryService.getOne(new LambdaQueryWrapper<ChatMemory>().eq(ChatMemory::getChildId, childId)
                .eq(ChatMemory::getFunModule, funModel.name())
                .eq(ChatMemory::getSocialSelfId, socialSelfId));
        if (Objects.nonNull(chatMemory)) {
            return R.ok(Map.of("memoryId", chatMemory.getId()));
        }
        Long chatMemoryId = IdWorker.getId();
        iChatMemoryService.save(ChatMemory.builder()
                .id(chatMemoryId)
                .childId(childId)
                .funModule(funModel.name())
                .socialSelfId(socialSelfId)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build());
        return R.ok(Map.of("memoryId", chatMemoryId));
    }

    /**
     * 文档分页
     *
     * @param current 当前页
     * @param size    每页数量
     * @return R<Page < KwDocument>>
     */
    @GetMapping("/history/page")
    public R<Page<ChatHistory>> historyPage(
            @RequestParam(value = "memoryId", required = false) @NotNull(message = "记忆ID不能为空") Long memoryId,
            @RequestParam(value = "current", required = false) @NotNull(message = "当前页码不能为空") Integer current,
            @RequestParam(value = "size", required = false) @NotNull(message = "每页数量不能为空") Integer size) {
        Long childId = SecurityContextHolder.get()
                .getChildId();
        boolean exists = iChatMemoryService.exists(new LambdaQueryWrapper<ChatMemory>().eq(ChatMemory::getId, memoryId)
                .eq(ChatMemory::getChildId, childId)
        );
        if (!exists) {
            return R.fail("记忆ID不存在");
        }
        Page<ChatHistory> page = iChatHistoryService.page(Page.of(current, size),
                new LambdaQueryWrapper<ChatHistory>()
                        .eq(ChatHistory::getMemoryId, memoryId)
                        .orderByDesc(ChatHistory::getId));
        return R.ok(page);
    }

}
